import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as path;
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';
import '../../data/models/album.dart';
import '../services/album_cache_service.dart';

/// 相册加载状态
enum AlbumLoadingStatus {
  /// 初始状态
  initial,

  /// 加载中
  loading,

  /// 加载完成
  loaded,

  /// 加载失败
  error,
}

/// 相册管理Provider
class AlbumProvider with ChangeNotifier {
  final AlbumCacheService _cacheService;

  List<Album> _albums = [];
  AlbumLoadingStatus _status = AlbumLoadingStatus.initial;
  String _errorMessage = '';
  int _loadedCount = 0;
  int _totalCount = 0;

  /// 相册列表
  List<Album> get albums => _albums;

  /// 加载状态
  AlbumLoadingStatus get status => _status;

  /// 错误信息
  String get errorMessage => _errorMessage;

  /// 已加载数量
  int get loadedCount => _loadedCount;

  /// 总数量
  int get totalCount => _totalCount;

  /// 加载进度百分比
  double get loadingProgress =>
      _totalCount > 0 ? _loadedCount / _totalCount * 100 : 0;

  /// 是否正在加载
  bool get isLoading => _status == AlbumLoadingStatus.loading;

  AlbumProvider({AlbumCacheService? cacheService})
    : _cacheService = cacheService ?? AlbumCacheService();

  /// 加载设备相册
  Future<void> loadAlbums({
    bool forceRefresh = false,
    bool autoBackupPhotos = true,
    bool autoBackupVideos = true,
  }) async {
    if (_status == AlbumLoadingStatus.loading) return;

    _setStatus(AlbumLoadingStatus.loading);
    _loadedCount = 0;
    _totalCount = 0;

    try {
      // 尝试从缓存加载
      if (!forceRefresh) {
        final cachedAlbums = await _cacheService.getAlbumCache();
        if (cachedAlbums != null && cachedAlbums.isNotEmpty) {
          _albums = cachedAlbums;
          _sortAlbums(autoBackupPhotos, autoBackupVideos);
          _setStatus(AlbumLoadingStatus.loaded);
          return;
        }
      }

      // 请求权限
      final result = await _requestPermission();
      if (!result) {
        _setError('无法访问相册，请授予权限');
        return;
      }

      // 获取相册列表
      final List<AssetPathEntity> paths = await PhotoManager.getAssetPathList(
        type: RequestType.common,
        hasAll: true,
      );

      _totalCount = paths.length;
      notifyListeners();

      // 清空旧数据，但保留已选择状态
      Map<String, bool> selectedStatusMap = {};
      for (var album in _albums) {
        selectedStatusMap[album.id] = album.isSelected;
      }
      _albums = [];

      // 处理每个相册
      for (var i = 0; i < paths.length; i++) {
        final path = paths[i];

        // 获取相册中的资产
        final List<AssetEntity> assets = await path.getAssetListRange(
          start: 0,
          end: await path.assetCountAsync,
        );

        if (assets.isEmpty) {
          _loadedCount++;
          notifyListeners();
          continue;
        }

        // 统计照片和视频数量
        int photoCount = 0;
        int videoCount = 0;
        AssetEntity? thumbnailAsset;

        for (var asset in assets) {
          if (asset.type == AssetType.image) {
            photoCount++;
            // 优先使用照片作为缩略图
            if (thumbnailAsset == null ||
                thumbnailAsset.type != AssetType.image) {
              thumbnailAsset = asset;
            }
          } else if (asset.type == AssetType.video) {
            videoCount++;
            // 如果还没有找到缩略图，使用视频
            if (thumbnailAsset == null) {
              thumbnailAsset = asset;
            }
          }
        }

        if (photoCount == 0 && videoCount == 0) {
          _loadedCount++;
          notifyListeners();
          continue;
        }

        // 获取缩略图
        Uint8List? thumbnailData;
        if (thumbnailAsset != null) {
          thumbnailData = await thumbnailAsset.thumbnailDataWithSize(
            const ThumbnailSize(200, 200),
            quality: 80,
          );
        }

        // 创建相册对象
        final String albumPath = path.id;
        final String albumId = _cacheService.generateAlbumId(albumPath);
        final String albumName = _getAlbumName(path.name, albumPath);

        final album = Album(
          id: albumId,
          name: albumName,
          path: albumPath,
          thumbnailData: thumbnailData,
          photoCount: photoCount,
          videoCount: videoCount,
          lastModified: DateTime.now(),
          isSelected:
              selectedStatusMap[albumId] ?? _isDefaultSelected(albumName),
        );

        _albums.add(album);
        _loadedCount++;
        _sortAlbums(autoBackupPhotos, autoBackupVideos);
        notifyListeners();
      }

      // 保存到缓存
      await _cacheService.saveAlbumCache(_albums);

      _setStatus(AlbumLoadingStatus.loaded);
    } catch (e) {
      debugPrint('加载相册失败: $e');
      _setError('加载相册失败: $e');
    }
  }

  /// 设置相册选择状态
  void setAlbumSelected(String albumId, bool selected) {
    final index = _albums.indexWhere((album) => album.id == albumId);
    if (index != -1) {
      _albums[index] = _albums[index].copyWith(isSelected: selected);
      notifyListeners();

      // 保存到缓存
      _cacheService.saveAlbumCache(_albums);
    }
  }

  /// 全选/取消全选相册
  void selectAllAlbums(bool selected) {
    for (var i = 0; i < _albums.length; i++) {
      _albums[i] = _albums[i].copyWith(isSelected: selected);
    }
    notifyListeners();

    // 保存到缓存
    _cacheService.saveAlbumCache(_albums);
  }

  /// 请求相册权限
  Future<bool> _requestPermission() async {
    // 先检查权限状态
    final status = await Permission.photos.status;

    // 如果已授权或有限授权，直接返回成功
    if (status.isGranted || status.isLimited) {
      return true;
    }

    // 如果是永久拒绝，让用户去设置中手动开启
    if (status.isPermanentlyDenied) {
      debugPrint('相册权限被永久拒绝，需要用户在设置中手动开启');
      return false;
    }

    // 显式请求权限
    debugPrint('正在请求相册权限...');
    final result = await Permission.photos.request();
    debugPrint('相册权限请求结果: $result');

    return result.isGranted || result.isLimited;
  }

  /// 设置状态
  void _setStatus(AlbumLoadingStatus status) {
    _status = status;
    if (status != AlbumLoadingStatus.error) {
      _errorMessage = '';
    }
    notifyListeners();
  }

  /// 设置错误
  void _setError(String message) {
    _status = AlbumLoadingStatus.error;
    _errorMessage = message;
    notifyListeners();
  }

  /// 获取相册名称
  String _getAlbumName(String name, String albumPath) {
    // 根据平台和路径格式化相册名称
    if (name.isNotEmpty) {
      return name;
    }

    // 尝试从路径获取名称
    try {
      final basename = path.basename(albumPath);
      return basename.isNotEmpty ? basename : '未命名相册';
    } catch (e) {
      return '未命名相册';
    }
  }

  /// 判断是否默认选择
  bool _isDefaultSelected(String albumName) {
    // 默认选择相机相册
    final lowerName = albumName.toLowerCase();
    return lowerName.contains('camera') ||
        lowerName.contains('相机') ||
        lowerName.contains('dcim');
  }

  /// 排序相册
  void _sortAlbums(bool autoBackupPhotos, bool autoBackupVideos) {
    _albums.sort((a, b) {
      // 按照有效项目数量排序（从大到小）
      final aCount = a.getEffectiveCount(
        autoBackupPhotos: autoBackupPhotos,
        autoBackupVideos: autoBackupVideos,
      );
      final bCount = b.getEffectiveCount(
        autoBackupPhotos: autoBackupPhotos,
        autoBackupVideos: autoBackupVideos,
      );

      if (aCount != bCount) {
        return bCount.compareTo(aCount);
      }

      // 数量相同时，按照最后修改时间排序（从新到旧）
      return b.lastModified.compareTo(a.lastModified);
    });
  }

  /// 刷新相册排序
  void refreshAlbumSort(bool autoBackupPhotos, bool autoBackupVideos) {
    _sortAlbums(autoBackupPhotos, autoBackupVideos);
    notifyListeners();
  }

  /// 强制刷新相册
  Future<void> forceRefreshAlbums({
    bool autoBackupPhotos = true,
    bool autoBackupVideos = true,
  }) async {
    await loadAlbums(
      forceRefresh: true,
      autoBackupPhotos: autoBackupPhotos,
      autoBackupVideos: autoBackupVideos,
    );
  }

  /// 清除缓存
  Future<void> clearCache() async {
    await _cacheService.clearAlbumCache();
  }
}
